<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="520px" class="merchant-dialog">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      class="merchant-form"
    >
      <el-form-item label="商家名称" prop="merchantName" required>
        <el-input v-model="formData.merchantName" placeholder="请输入商家名称" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone" required>
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input 
          v-model="formData.email" 
          placeholder="请输入电子邮箱" 
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" plain>取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'

/** 商家信息 表单 */
defineOptions({ name: 'MerchantForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  merchantName: undefined,
  contactPerson: undefined,
  phone: undefined,
  email: undefined,
  address: undefined,
  status: 0, // 默认状态为开启
})

const formRules = reactive({
  merchantName: [{ required: true, message: '商家名称不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '联系电话必须为数字', trigger: 'blur' }
  ],
  email: [
    { 
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
          callback(new Error('请输入正确的邮箱格式'))
        } else {
          callback()
        }
      }, 
      trigger: ['blur', 'change'] 
    }
  ]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MerchantApi.getMerchantById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MerchantVO
    if (formType.value === 'create') {
      await MerchantApi.createMerchant(data)
      message.success(t('common.createSuccess'))
    } else {
      await MerchantApi.updateMerchant(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    merchantName: undefined,
    contactPerson: undefined,
    phone: undefined,
    email: undefined,
    address: undefined,
    status: 0, // 重置时也设置默认状态为开启
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.merchant-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    
    .el-dialog__header {
      padding: 20px 20px 0;
      margin: 0;
      
      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .el-dialog__body {
      padding: 20px;
    }
    
    .el-dialog__footer {
      padding: 10px 20px 20px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
}

.merchant-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .el-form-item__label {
      font-weight: 500;
    }
    
    .el-input__wrapper,
    .el-select .el-input__wrapper {
      box-shadow: 0 0 0 1px var(--el-border-color) inset;
      
      &:hover {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    min-width: 88px;
    
    & + .el-button {
      margin-left: 12px;
    }
  }
}
</style>